﻿using FluentFTP;
using NPOI.HPSF;
using NPOI.SS.Formula.Functions;
using Org.BouncyCastle.Asn1.Cmp;
using Org.BouncyCastle.Crypto.Modes.Gcm;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar;

namespace FTP_progress
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            this.toolStripBnt_manualbackup.Click += async (sender, e) => await toolStripBnt_manualbackup_Click(sender, e);
            gb1.Location = gb2.Location = gb3.Location = gb4.Location = gb5.Location = gb6.Location;
        }

        private short pageNum = 0;
        Excelhelper myExcelhelper = new Excelhelper();
        DataSet ds;
        DataTable dt;
        int mark;
        PositiveEdge p = new PositiveEdge();
        public static string userName;

        /// <summary>
        /// 根据控价名称（string类型）寻找控件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="container"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public T FindControl<T>(Control container, string name) where T : Control
        {
            if (container == null || string.IsNullOrEmpty(name)) return null;
            if (container.Name == name && container is T result) return result;

            foreach (Control child in container.Controls)
            {
                var found = FindControl<T>(child, name);
                if (found != null)
                    return found;
            }
            return null;
        }
        /// <summary>
        /// 下载文件（主）
        /// </summary>
        /// <param name="server"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="fileExtensions"></param>
        /// <param name="localFilePath"></param>
        /// <param name="remoteFilePath"></param>
        /// <param name="pb"></param>
        /// <param name="lbePercent"></param>
        /// <param name="lblState"></param>
        private async Task StartDownload(string server, string username, string password, string fileExtensions, string localFilePath, string remoteFilePath, string pb, string lbePercent, string lblState)
        {
            ProgressBar progressBar = FindControl<ProgressBar>(panel1, pb);
            Label labelPercentage = FindControl<Label>(panel1, lbePercent);
            Label labelStatus = FindControl<Label>(panel1, lblState);
            FtpDownLoad downloader = new FtpDownLoad
            {
                FtpServerIp = server,
                Username = username,
                Password = password,
                FileExtensions = fileExtensions,  // 用斜杠分隔的扩展名
                LocalFolder = localFilePath,
                RemoteFolder = remoteFilePath,

                ProgressBar = progressBar,
                LabelPercentage = labelPercentage,
                LabelStatus = labelStatus
            };

            await downloader.DownloadAsync();
        }
        private void UpdateLabel(string message, Label lbl)
        {
            if (lbl.InvokeRequired)
            {
                lbl.Invoke(new Action(() => lbl.Text = message));
            }
            else
            {
                lbl.Text = message;
            }
        }

        // gitee相关配置参数
        //string sourceFolder = @"E:\backup"; // 源文件位置
        //string gitlabUrl = "https://gitee.com/binyongliang/study.git";
        //string repoPath = @"C:\LocalGitRepo\study";// 本地仓库路径最后一个文件夹必须与gitLab保持一致
        //string username = "binyongliang";         // Gitee 用户名
        //string pat = "BYL924902978";              // Gitee PAT
        //string logPath = @"E:\";
        //string logFileName = "diffLog";
        //string branchName = "master";//gitee分支名为master,gitlab为main

        // gitLab配置参数     
        //string sourceFolder = @"D:\test"; // 源文件位置
        //string gitlabUrl = "https://ccsmsgit.magna.global/dev/study.git";
        //string repoPath = @"C:\LocalGitRepo\study";// 本地仓库路径最后一个文件夹必须与gitLab保持一致
        //string username = "deanbin";         // GitLab 用户名
        //string pat = "WOSHIBIN-4321";        // GitLab PAT
        //string logPath = @"D:\";
        //string logFileName = "diffLog";
        //string branchName = "main";//gitee分支名为master,gitlab为main

        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
        // gitee相关配置参数
        public static string [] sourceFolders;
        public static string[] robots;
        public static string [] gitlabUrls;
        public static string repoPath;
        public static string []repoPaths;
        public static string username;
        public static string pat;
        public static string logPath;
        public static string logFileName;
        public static string []logFileNames;
        public static string branchName;
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//

        /// <summary>
        /// 窗口初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void MainForm_Load(object sender, EventArgs e)
        {
            userName = "nobody";
            toolStripBnt_Start.Image = Properties.Resources.start;
            //从Excel表格中获得数据
            pageNum = 1;
            btnNext.Enabled = btnPrevious.Enabled = false;
            gb1.Visible = true;
            gb6.Visible = gb5.Visible = gb4.Visible = gb3.Visible = gb2.Visible = false;

            RefreshUI();
            GetGitParam();
            Task.Run(() =>
            {
                while (true)
                {
                    UpdateLabel(DateTime.Now.ToLongTimeString(), lblDateTime);
                    UpdateLabel(userName, lblUserName);
                    if (userName == "administrator")
                    {
                        //***************************************//
                        if (toolStripBnt_Start.GetCurrentParent().InvokeRequired)
                        {
                            toolStripBnt_Start.GetCurrentParent().Invoke((MethodInvoker)delegate
                            {
                                toolStripBnt_Start.Enabled = true;
                            });
                        }
                        else
                        {
                            toolStripBnt_Start.Enabled = true;
                        }
                        //***************************************//
                        if (tSBLogin.GetCurrentParent().InvokeRequired)
                        {
                            tSBLogin.GetCurrentParent().Invoke((MethodInvoker)delegate
                            {
                                tSBLogin.Text = "Logout";
                            });
                        }
                        else
                        {
                            tSBLogin.Text = "Logout";
                        }

                        //***************************************//
                        if (tSBSetting.GetCurrentParent().InvokeRequired)
                        {
                            tSBSetting.GetCurrentParent().Invoke((MethodInvoker)delegate
                            {
                                tSBSetting.Enabled = true;
                            });
                        }
                        else
                        {
                            tSBSetting.Enabled = true;
                        }
                    }
                    else
                    {
                        //***************************************//
                        if (toolStripBnt_Start.GetCurrentParent().InvokeRequired)
                        {
                            toolStripBnt_Start.GetCurrentParent().Invoke((MethodInvoker)delegate
                            {
                                toolStripBnt_Start.Enabled = false;
                            });
                        }
                        else
                        {
                            toolStripBnt_Start.Enabled = false;
                        }
                        //***************************************//
                        if (tSBLogin.GetCurrentParent().InvokeRequired)
                        {
                            tSBLogin.GetCurrentParent().Invoke((MethodInvoker)delegate
                            {
                                tSBLogin.Text = "Login";
                            });
                        }
                        else
                        {
                            tSBLogin.Text = "Login";
                        }
                        //***************************************//
                        if (tSBSetting.GetCurrentParent().InvokeRequired)
                        {
                            tSBSetting.GetCurrentParent().Invoke((MethodInvoker)delegate
                            {
                                tSBSetting.Enabled = false;
                            });
                        }
                        else
                        {
                            tSBSetting.Enabled = false;
                        }
                    }
                    Thread.Sleep(100);
                }
            });
        }

        /// <summary>
        /// 添加控件
        /// </summary>
        /// <param name="gb"></param>
        /// <param name="startNum"></param>
        /// <param name="endNum"></param>
        private void AddControl(GroupBox gb, int startNum, int endNum)
        {
            for (int i = startNum; i < endNum; i++)
            {
                Label lbl = new Label();
                lbl.Name = "ID" + (i + 1);
                // lbl.Text = (i + 1).ToString();
                lbl.Location = new System.Drawing.Point(8, 42 + (i % 20) * 27);

                lbl.Size = new System.Drawing.Size(50, 24);
                lbl.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
                lbl.Font = new System.Drawing.Font("Arial", 9F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                lbl.ForeColor = System.Drawing.Color.FromArgb(64, 64, 64); // 自定义深灰色
                lbl.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
                gb.Controls.Add(lbl);

                //添加Robot name
                Label lbl1 = new Label();
                lbl1.Name = "Robot" + (i + 1);
                // lbl1.Text = (i + 1).ToString();
                lbl1.Location = new System.Drawing.Point(62, 42 + (i % 20) * 27);

                lbl1.Size = new System.Drawing.Size(96, 24);
                lbl1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
                lbl1.Font = new System.Drawing.Font("Arial", 9F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                lbl1.ForeColor = System.Drawing.Color.FromArgb(64, 64, 64); // 自定义深灰色
                lbl1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
                gb.Controls.Add(lbl1);

                //添加文件后缀
                Label comment = new Label();
                comment.Name = "Comment" + (i + 1);
                comment.Location = new System.Drawing.Point(162, 42 + (i % 20) * 27);
                comment.Size = new System.Drawing.Size(80, 24);
                comment.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
                comment.Font = new System.Drawing.Font("Arial", 10F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                comment.ForeColor = System.Drawing.Color.FromArgb(64, 64, 64); // 自定义深灰色
                comment.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
                gb.Controls.Add(comment);

                //server calibri light
                Label server = new Label();
                server.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
                server.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                server.ForeColor = System.Drawing.Color.FromArgb(64, 64, 64); // 自定义深灰色
                server.Location = new System.Drawing.Point(246, 42 + (i % 20) * 27);
                server.Name = "Server" + (i + 1);
                server.Size = new System.Drawing.Size(130, 24);
                // server.Text = "192.168.200.128";
                server.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
                gb.Controls.Add(server);

                //remote file path

                Label remoteFilePath = new Label();
                remoteFilePath.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
                remoteFilePath.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
                remoteFilePath.Location = new System.Drawing.Point(381, 42 + (i % 20) * 27);
                remoteFilePath.Name = "RemoteFilePath" + (i + 1);
                remoteFilePath.Size = new System.Drawing.Size(138, 24);
                remoteFilePath.ForeColor = System.Drawing.Color.FromArgb(64, 64, 64); // 自定义深灰色
                remoteFilePath.TabStop = true;
                //localFilePath.Text = "D:Recipe\\tdm_destacker\\HMI";
                remoteFilePath.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
                gb.Controls.Add(remoteFilePath);

                //local file path

                LinkLabel localFilePath = new LinkLabel();
                localFilePath.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
                localFilePath.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
                localFilePath.Location = new System.Drawing.Point(523, 42 + (i % 20) * 27);
                localFilePath.Name = "LocalFilePath" + (i + 1);
                localFilePath.Size = new System.Drawing.Size(138, 24);
                localFilePath.ForeColor = System.Drawing.Color.FromArgb(64, 64, 64); // 自定义深灰色
                localFilePath.TabStop = true;
                //localFilePath.Text = "D:Recipe\\tdm_destacker\\HMI";
                localFilePath.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
                localFilePath.VisitedLinkColor = Color.Purple;

                localFilePath.Click += (sender, e) => linkLable_Click(localFilePath, e);
                gb.Controls.Add(localFilePath);


                //gitlabURL

                Label gitlabURL = new Label();
                gitlabURL.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
                gitlabURL.Font = new System.Drawing.Font("Segoe UI", 8F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
                gitlabURL.Location = new System.Drawing.Point(665, 42 + (i % 20) * 27);
                gitlabURL.Name = "GitlabURL" + (i + 1);
                gitlabURL.Size = new System.Drawing.Size(235, 24);
                gitlabURL.ForeColor = System.Drawing.Color.FromArgb(64, 64, 64); // 自定义深灰色
                gitlabURL.TabStop = true;
                
                gitlabURL.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
                gb.Controls.Add(gitlabURL);



                //progress value
                Label pv = new Label();
                pv.AutoSize = true;
                pv.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
                pv.ForeColor = System.Drawing.Color.FromArgb(64, 64, 64); // 自定义深灰色
                pv.Location = new System.Drawing.Point(956, 46 + (i % 20) * 27);
                pv.Name = "Pv" + (i + 1);
                pv.Size = new System.Drawing.Size(40, 17);
                pv.Text = "0%";
                pv.BackColor = Color.Transparent;
                //pv.BringToFront();
                gb.Controls.Add(pv);

                //Progress
                ProgressBar pb = new ProgressBar();
                pb.Location = new System.Drawing.Point(904, 42 + (i % 20) * 27);
                pb.Name = "Progress" + (i + 1);
                pb.Size = new System.Drawing.Size(132, 24);
                // 初始化进度条
                pb.Minimum = 0;
                pb.Maximum = 100;
                //pb.SendToBack();
                gb.Controls.Add(pb);

                //result
                Label result = new Label();
                result.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
                result.Font = new System.Drawing.Font("Arial", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                result.Location = new System.Drawing.Point(1041, 42 + (i % 20) * 27);
                result.Name = "Result" + (i + 1);
                result.Size = new System.Drawing.Size(208, 24);
                result.ForeColor = System.Drawing.Color.FromArgb(64, 64, 64); // 自定义深灰色
                result.Text = "";
                result.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
                gb.Controls.Add(result);
            }
        }
        /// <summary>
        /// 超级链接
        /// </summary>
        /// <param name="linkLabel"></param>
        /// <param name="e"></param>
        private void linkLable_Click(LinkLabel linkLabel, EventArgs e)
        {
            try
            {
                Process.Start(linkLabel.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void previous_btn_Click(object sender, EventArgs e)
        {
            if (pageNum <= 1) return;
            pageNum--;

            switch (pageNum)
            {
                case 1:
                    gb1.Visible = true;
                    gb6.Visible = gb5.Visible = gb4.Visible = gb3.Visible = gb2.Visible = false;
                    break;

                case 2:
                    gb2.Visible = true;
                    gb6.Visible = gb5.Visible = gb4.Visible = gb3.Visible = gb1.Visible = false;
                    break;

                case 3:
                    gb3.Visible = true;
                    gb6.Visible = gb5.Visible = gb4.Visible = gb1.Visible = gb2.Visible = false;
                    break;

                case 4:
                    gb4.Visible = true;
                    gb6.Visible = gb5.Visible = gb1.Visible = gb3.Visible = gb2.Visible = false;
                    break;


                case 5:
                    gb5.Visible = true;
                    gb6.Visible = gb1.Visible = gb4.Visible = gb3.Visible = gb2.Visible = false;
                    break;

                case 6:
                    gb6.Visible = true;
                    gb1.Visible = gb5.Visible = gb4.Visible = gb3.Visible = gb2.Visible = false;
                    break;

                default:
                    gb1.Visible = true;
                    gb6.Visible = gb5.Visible = gb4.Visible = gb3.Visible = gb2.Visible = false;
                    break;

            }
            lbl_currentPage.Text = pageNum.ToString();
        }
        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void next_btn_Click(object sender, EventArgs e)
        {
            if (pageNum >= 6) return;
            pageNum++;

            switch (pageNum)
            {
                case 1:
                    gb1.Visible = true;
                    gb6.Visible = gb5.Visible = gb4.Visible = gb3.Visible = gb2.Visible = false;
                    break;

                case 2:
                    gb2.Visible = true;
                    gb6.Visible = gb5.Visible = gb4.Visible = gb3.Visible = gb1.Visible = false;
                    break;

                case 3:
                    gb3.Visible = true;
                    gb6.Visible = gb5.Visible = gb4.Visible = gb1.Visible = gb2.Visible = false;
                    break;

                case 4:
                    gb4.Visible = true;
                    gb6.Visible = gb5.Visible = gb1.Visible = gb3.Visible = gb2.Visible = false;
                    break;


                case 5:
                    gb5.Visible = true;
                    gb6.Visible = gb1.Visible = gb4.Visible = gb3.Visible = gb2.Visible = false;
                    break;

                case 6:
                    gb6.Visible = true;
                    gb1.Visible = gb5.Visible = gb4.Visible = gb3.Visible = gb2.Visible = false;
                    break;

                default:
                    gb1.Visible = true;
                    gb6.Visible = gb5.Visible = gb4.Visible = gb3.Visible = gb2.Visible = false;
                    break;
            }

            lbl_currentPage.Text = pageNum.ToString();
        }
        private void page_lbl_TextChanged(object sender, EventArgs e)
        {
            btnNext.Enabled = pageNum >= (int)Math.Ceiling((double)dt.Rows.Count / 20.0) ? false : true;
            btnPrevious.Enabled = pageNum <= 1 ? false : true;
        }

        private void tsbtnDataImport_Click(object sender, EventArgs e)
        {
            OpenFileDialog open = new OpenFileDialog();
            open.Filter = "Excel2007|*.xlsx|Excel2003(*.xls)|*.xls";
            if (open.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ds = myExcelhelper.ExcelToDataSet(open.FileName);
                //将数据写入数据库
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    Sqlite sql = new Sqlite();
                    //删除所有数据
                    sql.DeleteAll("tab", null);
                    //将EXCEL数据写入数据库
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        Dictionary<string, object> dictionary = new Dictionary<string, object>();
                        dictionary.Clear();//清空
                        // dictionary.Add("num", ds.Tables[0].Rows[i][0].ToString().Trim());
                        dictionary.Add("Robot", ds.Tables[0].Rows[i][1].ToString().Trim());
                        dictionary.Add("FileType", ds.Tables[0].Rows[i][2].ToString().Trim());
                        dictionary.Add("Server", ds.Tables[0].Rows[i][3].ToString().Trim());
                        dictionary.Add("LocalFilePath", ds.Tables[0].Rows[i][4].ToString().Trim());
                        dictionary.Add("RemoteFilePath", ds.Tables[0].Rows[i][5].ToString().Trim());
                        dictionary.Add("GitlabURL", ds.Tables[0].Rows[i][6].ToString().Trim());
                        sql.Insert("tab", dictionary);
                    }
                    //直接更新UI界面
                    RefreshUI();

                    MessageBox.Show("导入成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("导入未完成或失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        /// <summary>
        /// 获取所有子控件
        /// </summary>
        /// <param name="parent"></param>
        /// <returns></returns>
        public List<Control> GetAllChildControls(Control parent)
        {
            List<Control> controls = new List<Control>();
            foreach (Control child in parent.Controls)
            {
                controls.Add(child);
                controls.AddRange(GetAllChildControls(child));
            }
            return controls;
        }
        private async Task toolStripBnt_manualbackup_Click(object sender, EventArgs e)
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                if (tsbPushGit.GetCurrentParent().InvokeRequired)
                {
                    tsbPushGit.GetCurrentParent().Invoke((MethodInvoker)delegate
                    {
                        toolStripBnt_manualbackup.Enabled = false;
                        tsbPushGit.Enabled = false;  
                        tsbtnDataImport.Enabled=false;  
                        tSBSetting.Enabled=false;
                        tsbGitSet.Enabled=false;
                    });
                }
                else
                {
                    toolStripBnt_manualbackup.Enabled = false;
                    tsbPushGit.Enabled = false;
                    tsbtnDataImport.Enabled = false;
                    tSBSetting.Enabled = false;
                    tsbGitSet.Enabled = false;
                }

                //清空相关信息
                List<Control> allControls = GetAllChildControls(panel1);
                foreach (Control ctrl in allControls)
                {
                    if (ctrl.Name.Contains("Result"))
                        //ctrl.Text = String.Empty;
                        ctrl.Text = "";
                    if (ctrl is ProgressBar pb)
                        pb.Value = 0;
                    if (ctrl.Name.Contains("Pv"))
                        ctrl.Text = "0%";
                }

                Task[] tasks = new Task[dt.Rows.Count];
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    tasks[i] = StartDownload(dt.Rows[i][3].ToString().Trim(),
                        "anonymous", "",
                        dt.Rows[i][2].ToString().Trim(),
                        // @"D:\FtpDownloads\",
                        dt.Rows[i][4].ToString().Trim(),
                        //"md:/",
                        @dt.Rows[i][5].ToString().Trim(),
                        "Progress" + (i + 1).ToString().Trim(),
                        "Pv" + (i + 1).ToString().Trim(),
                        "Result" + (i + 1).ToString().Trim());
                }

                await Task.WhenAll(tasks);

                if (tsbPushGit.GetCurrentParent().InvokeRequired)
                {
                    tsbPushGit.GetCurrentParent().Invoke((MethodInvoker)delegate
                    {
                        toolStripBnt_manualbackup.Enabled = true;
                        tsbPushGit.Enabled = true;
                        tsbtnDataImport.Enabled = true;
                        tSBSetting.Enabled = true;
                        tsbGitSet.Enabled = true;
                    });
                }
                else
                {
                    toolStripBnt_manualbackup.Enabled = true;
                    tsbPushGit.Enabled = true;
                    tsbtnDataImport.Enabled = true;
                    tSBSetting.Enabled = true;
                    tsbGitSet.Enabled = true;
                }

               // MessageBox.Show("下载任务全部结束!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
               // MessageBox.Show("未导入相关参数!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void toolStripBnt_Start_Click(object sender, EventArgs e)
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                mark++;
                //CancellationTokenSource cts;
                if (mark % 2 == 1)
                {
                    //自动中
                    toolStripBnt_Start.Image = Properties.Resources.stop;//显示停止按钮
                    toolStripBnt_Start.Text = "自动停止";
                    toolStripBnt_Start.BackColor = Color.LightGreen;

                    //开启定时任务
                    //Task[] tasks = new Task[dt.Rows.Count];
                    Task task = Task.Run(async () =>
                     {
                         while (mark % 2 == 1)
                         {
                             p.CLK = DateTime.Now.ToShortTimeString() == "23:50" ? true : false;

                             if (p.Q)
                             {

                                 //for (int i = 0; i < dt.Rows.Count; i++)
                                 //{
                                 //    tasks[i] = StartDownload(dt.Rows[i][3].ToString().Trim(),
                                 //          "anonymous", "",
                                 //          dt.Rows[i][2].ToString().Trim(),
                                 //          // @"D:\FtpDownloads\",
                                 //          dt.Rows[i][4].ToString().Trim(),
                                 //          //"md:/",
                                 //          @dt.Rows[i][5].ToString().Trim(),
                                 //          "Progress" + (i + 1).ToString().Trim(),
                                 //          "Pv" + (i + 1).ToString().Trim(),
                                 //          "Result" + (i + 1).ToString().Trim());
                                 //}

                                 await toolStripBnt_manualbackup_Click(sender, e);

                                // await  Task.WhenAll(tasks);
                                 Thread.Sleep(1000);
                                 //自动推送到gitlab
                                 tsbPushGit_Click(sender, e);

                             }
                             Thread.Sleep(10000);
                         }
                     });
                }

                //取消定时任务
                if (mark % 2 == 0)
                {
                    //取消任务并更新UI
                    toolStripBnt_Start.Image = Properties.Resources.start;//显示启动按钮
                    toolStripBnt_Start.Text = "自动启动";
                    toolStripBnt_Start.BackColor = Color.Transparent;
                    //取消任务
                }
            }
            else
            {
                MessageBox.Show("未导入相关参数!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private void tSBLogin_Click(object sender, EventArgs e)
        {

            if (userName == "administrator")
            {
                userName = "nobody";
            }
            else
            {
                Login log = new Login();
                log.Show();
            }
        }

        public void ClearControlsExcept(Control parent, params Control[] exceptions)
        {
            foreach (Control c in parent.Controls.Cast<Control>().ToList()) // 使用ToList()避免在循环中修改集合
            {
                if (!exceptions.Contains(c))
                {
                    parent.Controls.Remove(c);
                    c.Dispose(); // 释放控件资源
                }
            }
        }
        /// <summary>
        /// 刷新UI
        /// </summary>
        private void RefreshUI()
        {
            Sqlite sql = new Sqlite();
            dt = sql.Select("tab", null, null);
            if (dt == null || dt.Rows.Count <= 0) return;

            //清空容器里面的控件
            ClearControlsExcept(gb1, label1, label2, label3, label4, label5, label6, label7, label49,label52);
            ClearControlsExcept(gb2, label8, label9, label10, label11, label12, label13, label14, label48,label50);
            ClearControlsExcept(gb3, label15, label16, label17, label18, label19, label20, label21, label47,label55);
            ClearControlsExcept(gb4, label22, label23, label24, label25, label26, label27, label28, label46,label53);
            ClearControlsExcept(gb5, label29, label30, label31, label32, label33, label34, label35, label45,label54);
            ClearControlsExcept(gb6, label36, label37, label38, label39, label40, label41, label42, label44,label56);


            int n = dt.Rows.Count;
            lbl_pageSum.Text = ((int)Math.Ceiling((double)n / 20.0)).ToString();

            if (n <= 20 && n >= 0)//1 PAGE
            {
                //page 1
                AddControl(gb1, 0, ((n % 20) == 0) ? 20 : n % 20);
                gb1.Height = 48+n*27;
            }
            else if (n <= 40 && n > 20)
            {
                //page 2
                AddControl(gb1, 0, 20);
                AddControl(gb2, 20, 20 + (((n % 20) == 0) ? 20 : n % 20));
                btnNext.Enabled = true;
                gb1.Height = 588;
                gb2.Height= 48 + (((n % 20) == 0) ? 20 : n % 20) * 27;
            }
            else if (n <= 60 && n > 40)
            {
                //page 3
                AddControl(gb1, 0, 20);
                AddControl(gb2, 20, 40);
                AddControl(gb3, 40, 40 + (((n % 20) == 0) ? 20 : n % 20));
                btnNext.Enabled = true;
                gb2.Height= gb1.Height = 588;
                gb3.Height = 48 + (((n % 20) == 0) ? 20 : n % 20) * 27;

            }
            else if (n <= 80 && n > 60)
            {
                //page 4
                AddControl(gb1, 0, 20);
                AddControl(gb2, 20, 40);
                AddControl(gb3, 40, 60);
                AddControl(gb4, 60, 60 + (((n % 20) == 0) ? 20 : n % 20));
                btnNext.Enabled = true;
                gb3.Height =gb2.Height = gb1.Height = 588;
                gb4.Height = 48 + (((n % 20) == 0) ? 20 : n % 20) * 27;
            }
            else if (n <= 100 && n > 80)
            {
                //page 5
                AddControl(gb1, 0, 20);
                AddControl(gb2, 20, 40);
                AddControl(gb3, 40, 60);
                AddControl(gb4, 60, 80);
                AddControl(gb5, 80, 80 + (((n % 20) == 0) ? 20 : n % 20));
                btnNext.Enabled = true;
                gb4.Height= gb3.Height = gb2.Height = gb1.Height = 588;
                gb5.Height = 48 + (((n % 20) == 0) ? 20 : n % 20) * 27;
            }
            else if (n <= 120 && n > 80)
            {
                //page 6
                AddControl(gb1, 0, 20);
                AddControl(gb2, 20, 40);
                AddControl(gb3, 40, 60);
                AddControl(gb4, 60, 80);
                AddControl(gb5, 80, 100);
                AddControl(gb6, 100, 100 + (((n % 20) == 0) ? 20 : n % 20));
                btnNext.Enabled = true;
                gb5.Height= gb4.Height = gb3.Height = gb2.Height = gb1.Height = 588;
                gb6.Height = 48 + (((n % 20) == 0) ? 20 : n % 20) * 27;
            }

            //分页填充数据

            if (dt != null && dt.Rows.Count > 0)
            {
                for (int row = 1; row <= dt.Rows.Count; row++)
                {
                    List<Control> allControls = GetAllChildControls(panel1);
                    foreach (Control ctrl in allControls)
                    {
                        if (ctrl.Name == "ID" + row.ToString()) ctrl.Text = dt.Rows[row - 1][0].ToString();

                        if (ctrl.Name == "Robot" + row.ToString()) ctrl.Text = dt.Rows[row - 1][1].ToString();

                        if (ctrl.Name == "Comment" + row.ToString()) ctrl.Text = dt.Rows[row - 1][2].ToString();

                        if (ctrl.Name == "Server" + row.ToString()) ctrl.Text = dt.Rows[row - 1][3].ToString();

                        if (ctrl.Name == "LocalFilePath" + row.ToString()) ctrl.Text = dt.Rows[row - 1][4].ToString();

                        if (ctrl.Name == "RemoteFilePath" + row.ToString()) ctrl.Text = dt.Rows[row - 1][5].ToString();

                        if (ctrl.Name == "GitlabURL" + row.ToString()) ctrl.Text = dt.Rows[row - 1][6].ToString();
                    }
                }
            }
            gb1.Visible = true;
            gb6.Visible = gb5.Visible = gb4.Visible = gb3.Visible = gb2.Visible = false;

            //  MessageBox.Show("参数导入成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        private void tSBSetting_Click(object sender, EventArgs e)
        {
            Setting setting = new Setting();
            // 3. 订阅事件（在父窗口中）
            setting.DataUpdated += UpdateParentData;

            // 避免内存泄漏：窗口关闭时取消订阅
            setting.FormClosed += (s, args) =>
            {
                setting.DataUpdated -= UpdateParentData;
            };
            setting.Show();
        }

        private void UpdateParentData()
        {
            // 确保UI操作在主线程执行
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(UpdateParentData));
                return;
            }
            // 实际更新UI的逻辑
            RefreshUI();
        }

        private async void tsbPushGit_Click(object sender, EventArgs e)
        {

            if (tsbPushGit.GetCurrentParent().InvokeRequired)
            {
                tsbPushGit.GetCurrentParent().Invoke((MethodInvoker)delegate
                {
                    toolStripBnt_manualbackup.Enabled = false;
                    tsbPushGit.Enabled = false;
                    tsbtnDataImport.Enabled = false;
                    tSBSetting.Enabled = false;
                    tsbGitSet.Enabled = false;
                });
            }
            else
            {
                toolStripBnt_manualbackup.Enabled = false;
                tsbPushGit.Enabled = false;
                tsbtnDataImport.Enabled = false;
                tSBSetting.Enabled = false;
                tsbGitSet.Enabled = false;
            }

            GetGitParam();

            Task[] tasks = new Task[dt.Rows.Count];

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                tasks[i]= StartPushToGit(sourceFolders[i], gitlabUrls[i], repoPaths[i], username, pat, logPath, logFileNames[i],robots[i], branchName);
            }

            await Task.WhenAll(tasks);

            if (tsbPushGit.GetCurrentParent().InvokeRequired)
            {
                tsbPushGit.GetCurrentParent().Invoke((MethodInvoker)delegate
                {
                    toolStripBnt_manualbackup.Enabled = true;
                    tsbPushGit.Enabled = true;
                    tsbtnDataImport.Enabled = true;
                    tSBSetting.Enabled = true;
                });
            }
            else
            {
                toolStripBnt_manualbackup.Enabled = true;
                tsbPushGit.Enabled = true;
                tsbtnDataImport.Enabled = true;
                tSBSetting.Enabled = true;
                tsbGitSet.Enabled = true;
            }
        }

        private async Task StartPushToGit(string sourceFolderPath, string repoUrl,string repoPath, string userName, string pat, string logPath,string logFileName, string deviceName,string branchName = "main")
        {
            await Task.Run(() =>
            {           
                GitLab gitLab = new GitLab();
                gitLab.PushFolderToGit(sourceFolderPath, repoUrl, repoPath, userName, pat, logPath, logFileName,deviceName, branchName);
            });
        }

        private void tsbGitSet_Click(object sender, EventArgs e)
        {
            GitSet gitSetForm = new GitSet();
            gitSetForm.Show();
        }

        private void GetGitParam()
        {
            //获得gitlab相关参数
            Sqlite sql = new Sqlite();
            DataTable tb = sql.Select("git");

            repoPath = tb.Rows[0][2].ToString().Trim();
            username = tb.Rows[0][3].ToString().Trim();
            pat = tb.Rows[0][4].ToString().Trim();
            logPath = tb.Rows[0][5].ToString().Trim();
            logFileName = tb.Rows[0][6].ToString().Trim();
            branchName = tb.Rows[0][7].ToString().Trim();

            //获得本地备份文件夹
            Sqlite sqlTab = new Sqlite();  
            DataTable dtTab= sqlTab.Select("tab");
            if (dtTab.Rows.Count > 0)
            {
                sourceFolders = dtTab.AsEnumerable()
                    .Select(row => row.Field<string>("LocalFilePath"))
                    .ToArray();
                //gitLab url
                gitlabUrls = dtTab.AsEnumerable()
                  .Select(row => row.Field<string>("GitlabURL"))
                  .ToArray();

                //获得机器人名称
                robots = dtTab.AsEnumerable()
                  .Select(row => row.Field<string>("Robot"))
                  .ToArray();

                //遍历gitLabUrl获得仓库名
                repoPaths = gitlabUrls.Select(repo => $"{repoPath}//{ExtractRepoName(repo)}").ToArray();
                //获得logNames
                logFileNames= gitlabUrls.Select(repo => $"{ExtractRepoName(repo)}{logFileName}").ToArray();

            }
        }

        private string ExtractRepoName(string gitUrl)
        {
            try
            {
                // 处理以.git结尾的URL
                if (gitUrl.EndsWith(".git"))
                {
                    gitUrl = gitUrl.Substring(0, gitUrl.Length - 4);
                }

                // 处理可能包含.git的URL参数
                if (gitUrl.Contains(".git?"))
                {
                    gitUrl = gitUrl.Split(new[] { ".git?" }, StringSplitOptions.None)[0];
                }

                // 移除末尾的斜杠
                gitUrl = gitUrl.TrimEnd('/');

                // 获取URL的最后一部分
                int lastSlashIndex = gitUrl.LastIndexOf('/');
                if (lastSlashIndex >= 0 && lastSlashIndex < gitUrl.Length - 1)
                {
                    return gitUrl.Substring(lastSlashIndex + 1);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"处理URL时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return null;
        }

       
    }
}
